<?php

namespace App\Models;


use Illuminate\Support\Facades\DB;

class UserShouting extends Base
{

    // 用户管理
    protected $table = 'user_shouting';

    // 缓存字段，用于搜索绑定的字段
    protected $cacheFields = ['id', 'uid', 'to_uid', 'status'];

    // 获取收听的用户id
    public function getShoutingUid($uid, $apply_type = '')
    {
        if(empty($uid)){
            return [];
        }

        // 查询
        if($apply_type){
            // 个人认证是三级分类
            $siteType = new SiteType();
            $typeInfo = $siteType->isCache(true)->oneFind(['id' => $apply_type]);
            // user_medium 媒体认证 30
            // user_expert 专家认证 31
            $apply_type1 = $apply_type;
            $apply_type2 = 0;
            if($typeInfo['channel'] == 'user_medium'){
                $apply_type1 = 30;
                $apply_type2 = $apply_type;
            } elseif($typeInfo['channel'] == 'user_expert'){
                $apply_type1 = 31;
                $apply_type2 = $apply_type;
            }

            // 获取缓存
            $args      = compact('uid', 'apply_type');
            $cacheName = $this->cacheKey('lists', $args);
            $lists     = $this->cacheClass()->getCache($cacheName);
            if(empty($lists)){
                $where = ['user.apply_type1' => $apply_type1, 'shouting.status' => 1, 'shouting.uid' => $uid];
                if($apply_type2){
                    $where[] = ['user.apply_type2', '=', $apply_type2];
                }
                $userDb = new User();
                $lists  = $userDb->from('user')->where($where)->select(['shouting.*'])
                                 ->join('user_shouting as shouting', 'shouting.to_uid', '=', 'user.id')->get()->toArray();
                $this->bangField(['uid'])->addCacheList($lists, $cacheName, $lists, 'list');
            }
            $uids = array_column($lists, 'to_uid');
        } else{
            $where = ['uid' => $uid, 'status' => 1];
            $lists = $this->bangField(['uid'])->getList($where, 0);
            $lists = is_object($lists) ? $lists->toArray() : $lists;
            $uids  = array_column($lists, 'to_uid');
        }

        return $uids;
    }

    // 关注(第二次点击，取消关注)
    public function onFollow($uid, $to_uid)
    {
        // 查看用户是否存在
        $userDb = new User();
        $where  = ['id' => $to_uid, 'status' => 1];
        $info   = $userDb->where($where)->first();
        if(empty($info)){
            return $this->return_false('用户不存在或者被禁用！');
        }

        $userDb  = new User();
        $modifDb = new UserModify();
        // 是否已经关注
        $where  = ['uid' => $uid, 'to_uid' => $to_uid];
        $isInfo = $this->where($where)->first();

        // 数据操作
        if(empty($isInfo)){
            $status   = 1;
            $follData = ['uid' => $uid, 'to_uid' => $to_uid, 'status' => 1];
            $numbers  = ['follow_no' => DB::raw('follow_no + 1')];
            $UNumbers = ['shy_no' => DB::raw('shy_no + 1')];
            $numCache = ['follow_no' => '+1'];
            $UNCache  = ['shy_no' => '+1'];
            $this->fill($follData);
        } else{
            if($isInfo['status'] == 1){
                $status   = 0;
                $follData = ['status' => 0];
                $numbers  = ['follow_no' => DB::raw('follow_no - 1')];
                $UNumbers = ['shy_no' => DB::raw('shy_no - 1')];
                $numCache = ['follow_no' => '-1'];
                $UNCache  = ['shy_no' => '-1'];
            } else{
                $status   = 1;
                $follData = ['status' => 1];
                $numbers  = ['follow_no' => DB::raw('follow_no + 1')];
                $UNumbers = ['shy_no' => DB::raw('shy_no + 1')];
                $numCache = ['follow_no' => '+1'];
                $UNCache  = ['shy_no' => '+1'];
            }
            $isInfo->fill($follData);
        }

        // 事务操作
        DB::beginTransaction();
        try{
            // 关注
            if(empty($isInfo)){
                $result = $this->save();
            } else{
                $result = $isInfo->save();
            }
            // 关注人数
            $userDb->where('id', $info->id)->update($UNumbers);
            $modifDb->where('uid', $info->id)->update($UNumbers);
            $modifDb->where('uid', $uid)->update($numbers);
            // 提交事务
            DB::commit();
        } catch(\Exception $e){
            // 回滚事务
            DB::rollback();
            $error = $this->getError() ?: $e->getMessage();

            return $this->return_false($error, 5000);
        }

        // 缓存操作
        //$userDb->reSaveCache($uid, $numCache);
        $data = ['uid' => $uid, 'to_uid' => $to_uid];
        $this->deleteCacheShow($data, $isInfo);
        $userDb->deleteCacheShow(['id' => [$to_uid, $uid]]);

        return $status;
    }

    // 获取用户的订阅用户（我关注的人）
    public function getFollow($where, $page = 1, $rows = 10, $order = "id DESC")
    {
        // 获取缓存
        $bang     = $this->bang;
        $is_cache = $this->is_cache || $bang;
        $args     = compact('where', 'page', 'rows', 'order');
        if($is_cache){
            $cacheName = $this->cacheKey('lists_getFollow', $args);
            $result    = $this->cacheClass()->getCache($cacheName);
        }
        // 检查是否已经绑定
        if(($result) && (!empty($result['list']))){
            $this->checkBangList($result['list'], $cacheName);
        }

        // 查询
        if(empty($result)){
            $query = $this->where($where)->forPage($page, $rows);
            $count = $this->where($where)->count();
            if(is_array($order)){

            } else{
                $order = explode(" ", $order);
                $query = $query->orderby($order[0], $order[1]);
            }
            $lists = $query->get()->toArray();
        } else{
            $lists = $result['table'];
        }


        // 获取用户
        $users = [];
        if($lists){
            $userDb = new User();
            $uids   = array_column($lists, 'to_uid');
            $lists  = array_column($lists, null, 'to_uid');
            $users  = $userDb->isCache(true)->getListInIds($uids);
            foreach($users as $key => $_user){
                $_userid = $_user['id'];
                $_row    = $lists[$_userid] ?? [];
                // 整理
                $users[$key]['follow_time'] = $_row['mtime'] ?? 0;
            }
        }

        $result = ['count' => $count, 'page' => $page, 'rows' => $rows, 'list' => $users, 'table' => $lists,];
        // 保存为缓存
        if($is_cache && $lists){
            $this->addCacheList($lists, $cacheName, $result, 'list');
            $userDb->addBangList($users, $cacheName);
        }

        return $result;
    }

    // 获取用户的粉丝（关注我的人）
    public function getFans($where, $page = 1, $rows = 10, $order = "id DESC")
    {
        // 获取缓存
        $bang     = $this->bang;
        $is_cache = $this->is_cache || $bang;
        $args     = compact('where', 'page', 'rows', 'order');
        if($is_cache){
            $cacheName = $this->cacheKey('lists_getFans', $args);
            $result    = $this->cacheClass()->getCache($cacheName);
        }
        // 检查是否已经绑定
        if(($result) && (!empty($result['list']))){
            $this->checkBangList($result['list'], $cacheName);
        }

        if(empty($result)){
            // 查询
            $query = $this->where($where)->forPage($page, $rows);
            $count = $this->where($where)->count();
            if(is_array($order)){

            } else{
                $order = explode(" ", $order);
                $query = $query->orderby($order[0], $order[1]);
            }
            $lists = $query->get()->toArray();
        } else{
            $lists = $result['table'];
        }


        // 获取用户
        $users = [];
        if($lists){
            $userDb = new User();
            $uids   = array_column($lists, 'uid');
            $users  = $userDb->isCache(true)->getListInIds($uids);
            $users  = array_values($users);
        }

        $result = ['count' => $count, 'page' => $page, 'rows' => $rows, 'list' => $users, 'table' => $lists,];
        // 保存为缓存
        if($is_cache && $lists){
            $this->addCacheList($lists, $cacheName, $result, 'list');
            $userDb->addBangList($users, $cacheName);
        }

        return $result;
    }

    // 定义验证操作
    public function rules()
    {

        $add = [
        ];

        $edit = [
        ];

        $info = [
        ];


        $rule = [
            'uid'    => 'required',
            'to_uid' => 'required',
        ];


        $msg = [
            'id'     => '编号',
            'uid'    => '用户id',
            'to_uid' => '被收听的用户id',
            'status' => '状态（1-是）',
            'ctime'  => '创建时间',
            'mtime'  => '修改时间',
        ];

        return ['rule' => $rule, 'msg' => $msg, 'add' => $add];
    }
}
